import time
import logging
import pytest
from common.request_util_test import RequestUtil
from common.test_yaml_util_test import YamlUtil
from common.read_values import TextUtil
from common.extension_component import ExtensionComponent, InstallationParams
from config import datas


class TestMultiClusterManagement:
    flag_multicluster_installed_stat = 0  # flag置0表示multi-cluster-service之前未安装，需要在本测试套临时安装。置1表示之前已安装，无需安装
    url_verify = "/rest/multicluster/v1beta1/clusters/host/kubeconfig"
    timeout = 300

    @pytest.mark.normal
    @pytest.mark.abnormal
    @pytest.mark.multicluster
    @pytest.mark.parametrize('valuesinfo',
                             TextUtil().read_value_yaml('values_multicluster.yaml'))
    def test_install_multicluster(self, valuesinfo):
        # 安装并检查
        res = ExtensionComponent.is_installed('multi-cluster-service')
        if res == False:
            """开始安装"""
            uri_install = "/rest/application-management/v1beta1/helm-releases/namespace/{namespace}/release/{release}"
            uri_install = uri_install.replace("{namespace}", datas.test_multicluster["namespace"])
            uri_install = uri_install.replace("{release}", datas.test_multicluster["release"])
            url_install = datas.baseUrl + uri_install
            method_install = "POST"
            headers_install = {"Content-Type": "application/json"}
            data_install = {
                "chartName": datas.test_multicluster["release"],
                "repoName": datas.test_multicluster["repoName"],
                "version": datas.test_multicluster["version"],
                "values": valuesinfo["data"]['values'],
            }
            params = InstallationParams(url_install, method_install, headers_install, data_install)
            res_install = ExtensionComponent.installing(params, datas.baseUrl + self.url_verify, self.timeout)
            assert res_install == True

    @pytest.mark.normal
    @pytest.mark.multicluster
    @pytest.mark.parametrize('clusterinfo',
                             YamlUtil().read_testcase_yaml('v25.06/multiclusterManagement/1_get_cluster_list.yaml'))
    def test_get_cluster_list(self, clusterinfo):
        # 获取集群列表接口-正常
        base_url = datas.baseUrl
        url = base_url + clusterinfo['request']['url']
        method = clusterinfo['request']['method']
        req = RequestUtil().send_request(method, url)
        assert req.status_code == clusterinfo['validate'][0]['equals']['status_code']

    @pytest.mark.abnormal
    @pytest.mark.multicluster
    @pytest.mark.parametrize('clusterinfo', YamlUtil().read_testcase_yaml(
        'v25.06/multiclusterManagement/1_get_cluster_list_exception.yaml'))
    def test_get_cluster_list_exception(self, clusterinfo):
        # 获取集群列表接口-异常
        base_url = datas.baseUrl
        url = base_url + clusterinfo['request']['url']
        method = clusterinfo['request']['method']
        req = RequestUtil().send_request(method, url)
        assert req.status_code == clusterinfo['validate'][0]['equals']['status_code']

    @pytest.mark.normal
    @pytest.mark.multicluster
    @pytest.mark.parametrize('clusterinfo',
                             YamlUtil().read_testcase_yaml('v25.06/multiclusterManagement/2_add_cluster.yaml'))
    @pytest.mark.parametrize('valuesinfo',
                             TextUtil().read_value_yaml('values_multicluster.yaml'))
    def test_add_cluster(self, clusterinfo, valuesinfo):
        # 纳管集群接口-正常
        base_url = datas.baseUrl
        url = base_url + clusterinfo['request']['url']
        method = clusterinfo['request']['method']
        header = clusterinfo['request']['header']
        clusterinfo['request']['data']['name'] = datas.test_multicluster['managed_cluster_name']
        clusterinfo['request']['data']['kubeconfig'] = valuesinfo['data']['kubeconfig']
        data = clusterinfo['request']['data']
        req = RequestUtil().send_request(method, url, headers=header, json=data)
        time.sleep(10)
        assert req.status_code == clusterinfo['validate'][0]['equals']['status_code']

    @pytest.mark.abnormal
    @pytest.mark.multicluster
    @pytest.mark.parametrize('clusterinfo', YamlUtil().read_testcase_yaml(
        'v25.06/multiclusterManagement/2_add_cluster_exception.yaml'))
    @pytest.mark.parametrize('valuesinfo',
                             TextUtil().read_value_yaml('values_multicluster.yaml'))
    def test_add_cluster_exception(self, clusterinfo, valuesinfo):
        # 纳管集群接口-异常
        base_url = datas.baseUrl
        url = base_url + clusterinfo['request']['url']
        method = clusterinfo['request']['method']
        header = clusterinfo['request']['header']
        if clusterinfo['request']['data']['name'] == '{managed_cluster_name}':
            clusterinfo['request']['data']['name'] = datas.test_multicluster['managed_cluster_name']
        clusterinfo['request']['data']['kubeconfig'] = valuesinfo['data']['kubeconfig']
        data = clusterinfo['request']['data']
        req = RequestUtil().send_request(method, url, headers=header, json=data)
        time.sleep(10)
        assert req.status_code == clusterinfo['validate'][0]['equals']['status_code']

    @pytest.mark.normal
    @pytest.mark.multicluster
    @pytest.mark.parametrize('clusterinfo',
                             YamlUtil().read_testcase_yaml('v25.06/multiclusterManagement/3_modify_cluster.yaml'))
    def test_modify_cluster(self, clusterinfo):
        # 修改集群标签接口-正常
        base_url = datas.baseUrl
        url = base_url + clusterinfo['request']['url'].replace('{managed_cluster_name}',
                                                               datas.test_multicluster['managed_cluster_name'])
        method = clusterinfo['request']['method']
        header = clusterinfo['request']['header']
        data = clusterinfo['request']['data']
        req = RequestUtil().send_request(method, url, headers=header, json=data)
        assert req.status_code == clusterinfo['validate'][0]['equals']['status_code']

    @pytest.mark.abnormal
    @pytest.mark.multicluster
    @pytest.mark.parametrize('clusterinfo', YamlUtil().read_testcase_yaml(
        'v25.06/multiclusterManagement/3_modify_cluster_exception.yaml'))
    def test_modify_cluster_exception(self, clusterinfo):
        # 修改集群标签接口-异常
        base_url = datas.baseUrl
        url = base_url + clusterinfo['request']['url'].replace('{managed_cluster_name}',
                                                               datas.test_multicluster['managed_cluster_name'])
        method = clusterinfo['request']['method']
        header = clusterinfo['request']['header']
        data = clusterinfo['request']['data']
        req = RequestUtil().send_request(method, url, headers=header, json=data)
        assert req.status_code == clusterinfo['validate'][0]['equals']['status_code']

    @pytest.mark.normal
    @pytest.mark.multicluster
    @pytest.mark.parametrize('clusterinfo',
                             YamlUtil().read_testcase_yaml('v25.06/multiclusterManagement/4_delete_cluster.yaml'))
    def test_delete_cluster(self, clusterinfo):
        # 解除集群纳管接口-正常
        base_url = datas.baseUrl
        url = base_url + clusterinfo['request']['url'].replace('{managed_cluster_name}',
                                                               datas.test_multicluster['managed_cluster_name'])
        method = clusterinfo['request']['method']
        req = RequestUtil().send_request(method, url)
        assert req.status_code == clusterinfo['validate'][0]['equals']['status_code']

    @pytest.mark.abnormal
    @pytest.mark.multicluster
    @pytest.mark.parametrize('clusterinfo', YamlUtil().read_testcase_yaml(
        'v25.06/multiclusterManagement/4_delete_cluster_exception.yaml'))
    def test_delete_cluster_exception(self, clusterinfo):
        # 解除集群纳管接口-异常
        base_url = datas.baseUrl
        url = base_url + clusterinfo['request']['url'].replace('{managed_cluster_name}',
                                                               datas.test_multicluster['managed_cluster_name'])
        method = clusterinfo['request']['method']
        req = RequestUtil().send_request(method, url)
        assert req.status_code == clusterinfo['validate'][0]['equals']['status_code']

    @pytest.mark.normal
    @pytest.mark.abnormal
    @pytest.mark.multicluster
    def test_uninstall_multicluster(self):
        # 卸载并检查
        uri_delete = ("/clusters/host/rest/application-management/v1beta1/helm-releases/"
                      "namespace/{namespace}/release/{release}")
        uri_delete = uri_delete.replace("{namespace}", datas.test_multicluster["namespace"])
        uri_delete = uri_delete.replace("{release}", datas.test_multicluster["release"])
        url_delete = datas.baseUrl + uri_delete
        method_delete = "DELETE"
        params = InstallationParams(url_delete, method_delete)
        res_uninstall = ExtensionComponent.uninstall(params, datas.baseUrl + self.url_verify, self.timeout)
        assert res_uninstall == True
